
<template>
	<view class="container" style="background-color: #f3f4f5;">
		<view style="background-color: #fff;padding: 15px;">
			<u-form :model="formData" :rules="rules" ref="form1">
				<u-form-item label="项目名称" labelWidth="70" borderBottom prop="title" required>
					<u--input v-model="formData.title" border="none" placeholder="请输入项目名称" />
				</u-form-item>
				<u-form-item label="业主姓名" labelWidth="70" borderBottom prop="name" required>
					<u--input v-model="formData.name" border="none" placeholder="请输入业主姓名" />
				</u-form-item>
				<u-form-item label="业主电话" labelWidth="70" borderBottom prop="tel" required>
					<u--input v-model="formData.tel" border="none" placeholder="请输入业主姓名" />
				</u-form-item>
				<u-form-item 
					label="省市县区:" 
					borderBottom 
					labelWidth="70" 
					@tap="cityShow = true"
					prop="cityName"
					required>
					<u--input 
						v-model="formData.cityName" 
						readonly
						border="none" 
						placeholder="请选择省市县区"></u--input>
					<!-- 城市选择 -->
					<u-picker 
						:show="cityShow" 
						ref="uPicker" 
						:columns="cityList" 
						keyName="name" 
						@confirm="cityConfirm" 
						@change="changeHandler" 
						@cancel="cityShow = false">
					</u-picker>
				</u-form-item>
				<u-form-item label="详细地址" labelWidth="70" borderBottom prop="address" required>
					<u--input v-model="formData.address" border="none" placeholder="请输入业主姓名" />
				</u-form-item>
				<u-form-item label="小区名称" labelWidth="70" borderBottom prop="village" required>
					<u--input v-model="formData.village" border="none" placeholder="请输入小区名称" />
				</u-form-item>
				<block v-if="departmentid != 5">
					<u-form-item
						label="开始时间" 
						labelWidth="70" 
						borderBottom 
						prop="startdate" 
						required
						>
						<u-datetime-picker
							:show="startDateShow"
							mode="date"
							v-model="defDate1"
							@confirm="confirmStartDate"
							@cancel="startDateShow = false"
						></u-datetime-picker>
						<u--input 
							@tap="startDateShowHandle" 
							v-model="formData.startdate" 
							border="none" 
							readonly
							placeholder="请选择开始时间" />
					</u-form-item>
					<u-form-item
						label="结束时间" 
						labelWidth="70" 
						borderBottom 
						prop="expectenddate" 
						required
						>
						<u-datetime-picker
							:show="endDateShow"
							mode="date"
							v-model="defDate2"
							@confirm="confirmEndDate"
							@cancel="endDateShow = false"
						></u-datetime-picker>
						<u--input 
							@tap="endDateShowHandle" 
							v-model="formData.expectenddate" 
							border="none" 
							readonly
							placeholder="请选择结束时间" />
					</u-form-item>
				</block>
				<u-button 
					type="warning" 
					@click="submit" 
					color="#232773"
					customStyle="margin: 10px 0"
					:loading="loading"
					loadingText="保存中">
					保 存
				</u-button>
			</u-form>
		</view>
	</view>
</template>

<script>
	import { getPage } from '../../utils/config';
	import { imageCdn } from '../../utils/api';
	import { prosimify, $toast, http, storage } from '../../utils/utils';
	import wxApi from '../../utils/wxApi';
	import api from '../../utils/api';
	const app = getApp();
	export default {
		data() {
			return {
				id:0,
				userid: 0,
				departmentid:null,
				companyid:null,
				isEdit:false,
				loading:false,
				formData:{
					cityName:''
				},
				proDetail:null,
				defDate1:Number(new Date()),
				defDate2:Number(new Date()),
				rules: {
					title: {
						type: 'string',
						required: true,
						message: '项目名称不能为空',
						trigger: ['blur', 'change']
					},
					name: {
						type: 'string',
						required: true,
						message: '业主姓名不能为空',
						trigger: ['blur', 'change']
					},
					tel: [
							{
								required: true, 
								message: '请输入手机号',
								trigger: ['change','blur'],
							},
							{
								validator: (rule, value, callback) => {
									return uni.$u.test.mobile(value);
								},
								message: '手机号码不正确',
								trigger: ['change','blur'],
							}
						],
					address: {
						type: 'string',
						required: true,
						message: '详细地址不能为空',
						trigger: ['blur', 'change']
					},
					cityName: {
						required: true,
						message: '城市不能为空',
						trigger: ['blur', 'change']
					},
					village: {
						type: 'string',
						required: true,
						message: '小区名称不能为空',
						trigger: ['blur', 'change']
					},
					/* startdate: {
						required: true,
						message: '项目开始日期不能为空',
						trigger: ['blur', 'change']
					},
					expectenddate: {
						required: true,
						message: '项目结束日期不能为空',
						trigger: ['blur', 'change']
					}, */
				},
				
				province_id:'',  //省份ID
				city_id:'',   //城市ID
				district_id:'',   //区/县ID
				 
				regionInfo:[],
				// 城市选择器
				cityShow: false,
				// 打开选择器显示默认城市
				cityList: [],

				cityLevel1: [],
				cityLevel2: [],
				cityLevel3: [],
				
				startDateShow:false,
				startdate:'',
				endDateShow:false,
				expectenddate:''
			}
		},
		onReady(){
			this.$refs.form1.setRules(this.rules);
		},
		
		onLoad(options){
			if (JSON.stringify(options) !== '{}'){
				console.log('dayin:options~~~~~~新增编辑项目页面onload',options)
				this.proDetail = options
				let { province_id,city_id,district_id } = options
				storage
				    .get('userInfo')
				    .then((res) => {
						console.log('登录信息--userInfo------->',res)
						this.userid = res.data.userid;
						// departmentid 1-管理 2-财务 3-监理 4-设计 5-业务
						this.departmentid = res.data.departmentid;
						this.companyid = res.data.companyid;
				    })
				if(options.id){
					this.id = options.id
					this.isEdit = true
					uni.setNavigationBarTitle({
					  title: '编辑项目'
					})
					
					this.province_id = province_id
					this.city_id = city_id
					this.district_id = district_id
					
					this.formData = {
						title:this.proDetail.title,
						name:this.proDetail.name,
						tel:this.proDetail.tel,
						address:this.proDetail.address,
						village:this.proDetail.village,
						startdate:this.proDetail.expectenddate.slice(0,10),
						expectenddate:this.proDetail.expectenddate.slice(0,10),
						cityName:this.proDetail.cityName
					}
				} else{
					uni.setNavigationBarTitle({
					  title: '新增项目'
					})
				}
			}
			this.getRegionInfo();
		},
		methods: {
			
			/**
			 * 获取地区
			 */
			getRegionInfo() {
			    storage
			        .get('regionInfo')
			        .then((res) => {
			    		this.regionInfo = res;
						console.log('storage--城市数据------------',res)
						this.initCityData();
			        })
			        .catch((res) => {
			            http.get(
			                api.default,
			                {
			                    data: {
			                        action: 'district'
			                    }
			                },
			                false
			            ).then((res) => {
			                const { data } = res.data;
			    			this.regionInfo = data;
							storage.set('regionInfo', data);
			                console.log('storage--城市数据------------data',data)
							this.initCityData();
			            });
			        });
			},
			// 城市选择器
			initCityData() {
				// 遍历城市js
				this.regionInfo.forEach((item1, index1) => {
					let temp2 = [];
					this.cityLevel1.push({name:item1.name,id:item1.id});
					let temp4 = [];
					let temp3 = [];
					// 遍历市
					item1.list.forEach((item2, index2) => {
						temp2.push({name:item2.name,id:item2.id});
						// 遍历区
						item2.list.forEach((item3, index3) => {
							temp3.push({name:item3.name,id:item3.id});
						})
						temp4[index2] = temp3;
						temp3 = [];
					})
					this.cityLevel3[index1] = temp4;
					this.cityLevel2[index1] = temp2;
				})
				// 选择器默认城市
				this.cityList.push(this.cityLevel1, this.cityLevel2[0], this.cityLevel3[0][0]);
			},

			// 选中时执行
			changeHandler(e) {
				const {
					columnIndex,
					index,
					indexs,
					value,
					values,
					// 微信小程序无法将picker实例传出来，只能通过ref操作
					picker = this.$refs.uPicker
				} = e;
				console.log('选中时执行----------',e)
				if (columnIndex === 0) { // 选择第一列数据时
					// 设置第二列关联数据
					picker.setColumnValues(1, this.cityLevel2[index]);
					// 设置第三列关联数据
					picker.setColumnValues(2, this.cityLevel3[index][columnIndex]);
				} else if (columnIndex === 1) { // 选择第二列数据时
					// 设置第三列关联数据
					picker.setColumnValues(2, this.cityLevel3[indexs[0]][index]);
				}
			},

			// 单击确认按钮时执行
			cityConfirm(e) {
				// 输出数组 [省, 市, 区]
				console.log('dayin:cityConfirm~~~~~~',e);
				var cityNameArr = e.value.map(item=>item.name)
				var cityIdArr = e.value.map(item=>item.id)
				this.formData.cityName = cityNameArr.join("-");
				this.province_id = cityIdArr[0]
				this.city_id = cityIdArr[1]
				this.district_id = cityIdArr[2]
				// 隐藏城市选择器
				this.cityShow = false;
			},
			
			// 确认开始时间
			confirmStartDate(e){
				console.log('确认开始时间---------',e)
				var dateS = this.$com.formatTimestamp(e.value,'Y-m-d')
				console.log('确认开始时间---------',dateS)
				this.formData.startdate = dateS
				this.startDateShow = false;
			},
			// 确认结束时间
			confirmEndDate(e){
				console.log('确认结束时间---------',e)
				var dateS = this.$com.formatTimestamp(e.value,'Y-m-d')
				console.log('确认结束时间---------',dateS)
				this.formData.expectenddate = dateS
				this.endDateShow = false;
			},
			
			startDateShowHandle(){
				this.startDateShow = true
			},
			endDateShowHandle(){
				this.endDateShow = true
			},
			
			submit() {
				let that = this
				// 如果有错误，会在catch中返回报错信息数组，校验通过则在then中返回true
				this.$refs.form1.validate().then(res => {
			
					uni.showLoading({
						title: '保存中...',
						mask: true
					});
					let { userid,id,province_id,city_id,district_id }  = that
					console.log('province_id,city_id,district_id',province_id,city_id,district_id)
					let { title,name,tel,address,village,startdate,expectenddate } = that.formData;
					let parms = {
						action: 'addproject',
						id,
						userid,
						title,
						name,
						tel,
						address,
						village,
						province_id,
						city_id,
						district_id
					};
					if(this.departmentid!=5){
						parms.startdate = startdate;
						parms.expectenddate = expectenddate;
					}
					this.loading = true
					http.post(api.default, { data: parms }).then(res=>{
						console.log('dayin:res~~~~~~~',res)
						const { data } = res.data;
						if (res.data.code == 0) {
						    $toast(`保存成功`, {
						        icon: 'success',
						        times: 300
						    }).then(() => {
								console.log('companyidcompanyidcompanyid',this.companyid)
								wxApi.reLaunch(getPage.detail,{ userid:this.userid,id:res.data.data,companyid:this.companyid,departmentid:this.departmentid });
						    });
						} else {
						    $toast(res.errmsg);
						}
					}).finally(()=>this.loading = false)
				}).catch(errors => {
					console.log('err',errors)
					uni.$u.toast('请填写完整的信息')
				})
			},
		}
	}
</script>

<style>
	.submit_box{
		position: relative;
		bottom: 0;
	}
</style>
